﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AvatarHelper;
using Avatar.Model;

public partial class Management_ENewsPaperPublish : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            panel_Edit.Visible = false;
        }
    }
    protected void btn_AddNew_Click(object sender, EventArgs e)
    {
        panel_Edit.Visible = true;
    }
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrEmpty(txt_Content.Value)) throw new Exception("内容不能为空");

            using (var _adc = DBHelper.GetDataContext())
            {
                var _id = string.IsNullOrEmpty(txt_ID.Value) ? 0 : Convert.ToInt32(txt_ID.Value);
                var _news = _adc.ENewsPaper.FirstOrDefault(n => n.ID == _id);
                if (_news == null)
                {
                    var _category = _adc.ENewsPaperConfig.FirstOrDefault();
                    if (_category != null)
                    {
                        _news = new ENewsPaper();

                        _news.Content = txt_Content.Value;
                        _news.PublishDate = DateTime.Now;
                        _news.PaperCategoryID = _category.ID;
                        _news.Order = _adc.ENewsPaper.FirstOrDefault() == null ? 1 : _adc.ENewsPaper.Max(n => n.Order) + 1;

                        _adc.ENewsPaper.InsertOnSubmit(_news);
                    }
                    else
                    {

                    }

                }
                else
                {
                    _news.Content = txt_Content.Value;
                }
                _adc.SubmitChanges();
            }
            txt_Content.Value = "";
            panel_Edit.Visible = false;
            GridView1.DataBind();
        }
        catch (Exception _e)
        {
            lbl_Error.Text = "错误:" + _e.Message;
        }
    }
    protected void btn_Edit_Click(object sender, EventArgs e)
    {
        var _btn = sender as Button;
        var _id = string.IsNullOrEmpty(_btn.CommandArgument) ? 0 : Convert.ToInt32(_btn.CommandArgument);
        using (var _adc = DBHelper.GetDataContext())
        {
            var _news = _adc.ENewsPaper.FirstOrDefault(n => n.ID == _id);
            if (_news != null)
            {
                txt_Content.Value = _news.Content;
                txt_ID.Value = _news.ID.ToString();

                panel_Edit.Visible = true;
            }
            else
            {
                Response.Redirect(Request.Url.ToString());
            }
        }
    }
}
